package com.oss.demo.controller;

import com.oss.demo.utils.OssManagerUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/6/24 10:50
 */
@Controller
@RequestMapping("/file/api")
public class FileController
{
    private static final Log log = LogFactory.getLog(FileController.class);

    @GetMapping("/getlist")
    @ResponseBody
    public List<?> get(){
        return OssManagerUtil.getPic();
    }
    /**
     * 文件上传到阿里oss
     */
    @PostMapping("/uploadFiletoOss")
    @ResponseBody
    public String uploadFiletoOss(@RequestParam("file")MultipartFile file)throws IOException{
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        fileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
        String url = OssManagerUtil.uploadImage(fileName,file.getInputStream().available(),file.getInputStream());
        return url;
    }

    /*单文件上传*/
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file)
    {
        try
        {
            if (file.isEmpty())
            {
                return "空文件夹！";
            }
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
            log.info("上传的文件名为：" + originalFilename + "\n   后缀为:" + suffixName);
            String filepath = "D:\\";
            String path = filepath + originalFilename;
            log.info("path{}" + path);

            File dest = new File(path);
            log.info("{dest:}" + dest);

            if (!dest.getParentFile().exists())
            {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            return "上传成功！";
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return "上传失败！";
    }

    /*多文件上传*/
    @PostMapping("/uploads")
    @ResponseBody
    public String uploads(MultipartFile[] files)
    {
        String filepath = "D:\\";
        File folder = new File(filepath);
        if (!folder.exists())
        {
            folder.mkdirs();
        }
        for (MultipartFile file : files)
        {
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String newName = UUID.randomUUID().toString()
                    + originalFilename.substring(originalFilename.lastIndexOf("."));
            try
            {
                file.transferTo(new File(folder, newName));
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return "success";
    }

    /*文件下载*/
    @GetMapping("/download")
    public String downloadFile(HttpServletRequest req, HttpServletResponse resp)
    {
        String fileName = "";
        File file = new File("E:\\图片\\psb (9).jpg");
        if (file.exists())
        {
            resp.setContentType("application/force-download");
            resp.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] bytes = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try
            {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                ServletOutputStream os = resp.getOutputStream();
                int i = bis.read(bytes);
                while (i != -1)
                {
                    os.write(bytes, 0, i);
                    i = bis.read(bytes);
                }
                return "下载成功！";
            } catch (Exception e)
            {
                e.printStackTrace();
            } finally
            {
                try
                {
                    if (fis != null)
                    {
                        fis.close();
                    }
                    if (bis != null)
                    {
                        bis.close();
                    }
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return "失败！";
    }

    @RequestMapping("/")
    public String index()
    {
        return "index";
    }
}
